package com.taiji.dianthus.service.sms.impl;

import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.dao.sms.SmsAccountRepository;
import com.taiji.dianthus.domain.sms.SmsAccount;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.service.sms.SmsAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName SmsInfoServiceImnpl
 * @Description
 * @Author H.M
 * @Date 2020/7/15
 */
@Service
public class SmsAccountServiceImpl implements SmsAccountService {

    @Value("${out_invalid.back.time}")
    private Integer outInvalidBackTime;//外部----短信账号回复失效时间 单位天  1

    @Value("${inline_invalid.back.time}")
    private Integer inlineInvalidBackTime;//外部----短信账号回复失效时间 单位天  1

    @Value("${base_number}")
    private String baseNumber;//短信基础号码

    @Autowired
    private SmsAccountRepository smsAccountRepository;

    @Override
    public SmsAccount getInvalidBackAccount() {
        /*当前使用最新开的短信账号*/
        SmsAccount smsAccount = null;
        Sort sort = new Sort(Sort.Direction.ASC, "sort_number");
        Pageable pageable = PageRequest.of(0, 1, sort);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -inlineInvalidBackTime);
        List<SmsAccount> smsAccountList = smsAccountRepository.getInvalidBackAccount(pageable, calendar.getTime());
        if (smsAccountList.size() > 0) {
            smsAccount = smsAccountList.get(0);
        }
        return smsAccount;
    }

    @Override
    public SmsAccount getIdByMobile(String addSerial) {
        //电信和联通上行回复号码是106930194010413  截取后几位扩展码
        if (!addSerial.startsWith(baseNumber)) {
            addSerial = baseNumber + addSerial.substring(15);
        }
        System.out.println("上行短信账号：" + addSerial);
        return smsAccountRepository.getIdByMobile(addSerial);
    }

    @Override
    public SmsAccount getById(String smsAccountId) {
        return smsAccountRepository.getOne(smsAccountId);
    }

    @Override
    public void updateUseTimeById(String id, Date date) {
        smsAccountRepository.updateUseTimeById(id, date);
    }

    @Override
    public SmsAccount getInvalidBackAccountOutCall() {
        SmsAccount smsAccount = null;
        Sort sort = new Sort(Sort.Direction.ASC, "sort_number");
        Pageable pageable = PageRequest.of(0, 1, sort);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -outInvalidBackTime);
        List<SmsAccount> smsAccountList = smsAccountRepository.getInvalidBackAccountOutCall(pageable, calendar.getTime());
        if (smsAccountList.size() > 0) {
            smsAccount = smsAccountList.get(0);
        }
        return smsAccount;
    }

    @Override
    public BusinessMessage list(Integer pageSize, Integer currentPage, String name, String addSerial) {
        BusinessMessage message = new BusinessMessage();
        try {
            Sort sort = new Sort(Sort.Direction.DESC, "useTime").and(new Sort(Sort.Direction.ASC, "sortNumber"));
            //分页参数
            Pageable pageable = PageRequest.of(currentPage, pageSize, sort);
            Page<SmsAccount> logPage;
            //创建查询参数
            Specification<SmsAccount> spec = (Root<SmsAccount> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                List<Predicate> pl = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(name)) {
                    pl.add(cb.like(root.<String>get("userAccount"), "%" + name + "%"));
                }
                if (!StringUtils.isEmpty(addSerial)) {
                    pl.add(cb.like(root.<String>get("extendNumber"), "%" + addSerial + "%"));
                }
                pl.add(cb.equal(root.<String>get("enableFlag"), 1));

                return cb.and(pl.toArray(new Predicate[0]));
            };
            logPage = smsAccountRepository.findAll(spec, pageable);
            message.setMsg("查询短信账号列表成功");
            message.setData(logPage);
            message.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("查询注册应用列表失败");
        } finally {
            return message;
        }

    }

    @Override
    public BusinessMessage saveAccount(SmsAccount smsAccount, DSysUser dSysUser) {
        BusinessMessage message = new BusinessMessage();
        smsAccount.setEnableFlag(1);
        try {
            smsAccount.setAddSerial(smsAccount.getBaseNumber() + smsAccount.getExtendNumber());
            smsAccountRepository.saveAndFlush(smsAccount);
            message.setSuccess(true);
            message.setMsg("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("系统异常，保存失败");
        }
        return message;
    }

    @Override
    public BusinessMessage deleteById(String id) {
        BusinessMessage message = new BusinessMessage();
        try {
            smsAccountRepository.updateFlag(id);
            message.setSuccess(true);
            message.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("系统异常，删除失败");
        }
        return message;
    }

    @Override
    public BusinessMessage checkAddSerial(String baseNumber, String extendNumber, String id) {
        BusinessMessage message = new BusinessMessage();
        List<SmsAccount> list = null;
        if (StringUtils.isEmpty(id)) {
            list = smsAccountRepository.getByAppNameByAdd(baseNumber, extendNumber);
        } else {
            list = smsAccountRepository.getByAppNameByEdit(baseNumber, extendNumber, id);
        }
        if (list != null && list.size() > 0) {
            message.setSuccess(true);
        }
        return message;
    }
}
